using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using ChatBackend.Services;
using ChatBackend.DTOs;
using System.Security.Claims;

namespace ChatBackend.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class ChatController : ControllerBase
    {
        private readonly IChatService _chatService;

        public ChatController(IChatService chatService)
        {
            _chatService = chatService;
        }

        [HttpPost("rooms")]
        public async Task<ActionResult<ChatRoomDto>> CreateChatRoom([FromBody] CreateChatRoomDto createChatRoomDto)
        {
            try
            {
                var userId = GetUserId();
                if (!userId.HasValue)
                {
                    return Unauthorized();
                }

                var chatRoom = await _chatService.CreateChatRoomAsync(userId.Value, createChatRoomDto);
                return Ok(chatRoom);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "创建聊天室失败", error = ex.Message });
            }
        }

        [HttpGet("rooms")]
        public async Task<ActionResult<List<ChatRoomDto>>> GetUserChatRooms()
        {
            try
            {
                var userId = GetUserId();
                if (!userId.HasValue)
                {
                    return Unauthorized();
                }

                var chatRooms = await _chatService.GetUserChatRoomsAsync(userId.Value);
                return Ok(chatRooms);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "获取聊天室列表失败", error = ex.Message });
            }
        }

        [HttpGet("rooms/{chatRoomId}")]
        public async Task<ActionResult<ChatRoomDto>> GetChatRoom(int chatRoomId)
        {
            try
            {
                var userId = GetUserId();
                if (!userId.HasValue)
                {
                    return Unauthorized();
                }

                var chatRoom = await _chatService.GetChatRoomAsync(chatRoomId, userId.Value);
                if (chatRoom == null)
                {
                    return NotFound(new { message = "聊天室不存在或您没有访问权限" });
                }

                return Ok(chatRoom);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "获取聊天室信息失败", error = ex.Message });
            }
        }

        [HttpPost("rooms/direct")]
        public async Task<ActionResult<ChatRoomDto>> GetOrCreateDirectChat([FromBody] CreateDirectChatDto createDirectChatDto)
        {
            try
            {
                var userId = GetUserId();
                if (!userId.HasValue)
                {
                    return Unauthorized();
                }

                var chatRoom = await _chatService.GetOrCreateDirectChatAsync(userId.Value, createDirectChatDto.TargetUserId);
                return Ok(chatRoom);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { message = ex.Message });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "创建直接聊天失败", error = ex.Message });
            }
        }

        [HttpPost("messages")]
        public async Task<ActionResult<MessageDto>> SendMessage([FromBody] SendMessageDto sendMessageDto)
        {
            try
            {
                var userId = GetUserId();
                if (!userId.HasValue)
                {
                    return Unauthorized();
                }

                var message = await _chatService.SendMessageAsync(userId.Value, sendMessageDto);
                return Ok(message);
            }
            catch (UnauthorizedAccessException ex)
            {
                return Forbid(ex.Message);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "发送消息失败", error = ex.Message });
            }
        }

        [HttpGet("rooms/{chatRoomId}/messages")]
        public async Task<ActionResult<ChatHistoryDto>> GetChatHistory(int chatRoomId, [FromQuery] int pageNumber = 1, [FromQuery] int pageSize = 50)
        {
            try
            {
                var userId = GetUserId();
                if (!userId.HasValue)
                {
                    return Unauthorized();
                }

                var chatHistory = await _chatService.GetChatHistoryAsync(chatRoomId, userId.Value, pageNumber, pageSize);
                return Ok(chatHistory);
            }
            catch (UnauthorizedAccessException ex)
            {
                return Forbid(ex.Message);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "获取聊天记录失败", error = ex.Message });
            }
        }

        [HttpPost("rooms/{chatRoomId}/join")]
        public async Task<ActionResult> JoinChatRoom(int chatRoomId)
        {
            try
            {
                var userId = GetUserId();
                if (!userId.HasValue)
                {
                    return Unauthorized();
                }

                var success = await _chatService.JoinChatRoomAsync(chatRoomId, userId.Value);
                if (success)
                {
                    return Ok(new { message = "成功加入聊天室" });
                }
                else
                {
                    return BadRequest(new { message = "加入聊天室失败" });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "加入聊天室失败", error = ex.Message });
            }
        }

        [HttpPost("rooms/{chatRoomId}/leave")]
        public async Task<ActionResult> LeaveChatRoom(int chatRoomId)
        {
            try
            {
                var userId = GetUserId();
                if (!userId.HasValue)
                {
                    return Unauthorized();
                }

                var success = await _chatService.LeaveChatRoomAsync(chatRoomId, userId.Value);
                if (success)
                {
                    return Ok(new { message = "成功离开聊天室" });
                }
                else
                {
                    return BadRequest(new { message = "离开聊天室失败" });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "离开聊天室失败", error = ex.Message });
            }
        }

        [HttpPost("rooms/{chatRoomId}/mark-read")]
        public async Task<ActionResult> MarkAsRead(int chatRoomId)
        {
            try
            {
                var userId = GetUserId();
                if (!userId.HasValue)
                {
                    return Unauthorized();
                }

                var success = await _chatService.MarkAsReadAsync(chatRoomId, userId.Value);
                if (success)
                {
                    return Ok(new { message = "标记为已读成功" });
                }
                else
                {
                    return BadRequest(new { message = "标记为已读失败" });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "标记为已读失败", error = ex.Message });
            }
        }

        [HttpGet("rooms/{chatRoomId}/members")]
        public async Task<ActionResult<List<UserDto>>> GetChatRoomMembers(int chatRoomId)
        {
            try
            {
                var userId = GetUserId();
                if (!userId.HasValue)
                {
                    return Unauthorized();
                }

                var members = await _chatService.GetChatRoomMembersAsync(chatRoomId, userId.Value);
                return Ok(members);
            }
            catch (UnauthorizedAccessException ex)
            {
                return Forbid(ex.Message);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "获取聊天室成员失败", error = ex.Message });
            }
        }

        [HttpDelete("messages/{messageId}")]
        public async Task<ActionResult> DeleteMessage(int messageId)
        {
            try
            {
                var userId = GetUserId();
                if (!userId.HasValue)
                {
                    return Unauthorized();
                }

                var success = await _chatService.DeleteMessageAsync(messageId, userId.Value);
                if (success)
                {
                    return Ok(new { message = "消息删除成功" });
                }
                else
                {
                    return BadRequest(new { message = "消息删除失败" });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "消息删除失败", error = ex.Message });
            }
        }

        [HttpPut("messages/{messageId}")]
        public async Task<ActionResult<MessageDto>> EditMessage(int messageId, [FromBody] EditMessageDto editMessageDto)
        {
            try
            {
                var userId = GetUserId();
                if (!userId.HasValue)
                {
                    return Unauthorized();
                }

                var editedMessage = await _chatService.EditMessageAsync(messageId, userId.Value, editMessageDto.Content);
                if (editedMessage != null)
                {
                    return Ok(editedMessage);
                }
                else
                {
                    return BadRequest(new { message = "消息编辑失败" });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "消息编辑失败", error = ex.Message });
            }
        }

        private int? GetUserId()
        {
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            return int.TryParse(userIdClaim, out var userId) ? userId : null;
        }
    }

    public class CreateDirectChatDto
    {
        public int TargetUserId { get; set; }
    }

    public class EditMessageDto
    {
        public string Content { get; set; } = string.Empty;
    }
}
